﻿package Common
{
	import flash.display.*;
	import flash.events.*;
 
	/**
	 * отслеживание нажатых клавиш
	 * @author Yevgeniy Logachev
	 */
	public class Input
	{
		private static var 	m_keys:Array 		= [];
		private static var 	m_stage:Stage		= null;
		private static var 	m_enabled:Boolean 	= true;
		
		public static const KEY_DOWN:int 		= 40;
		public static const KEY_UP:int 			= 38;
		public static const KEY_LEFT:int 		= 37;
		public static const KEY_RIGHT:int 		= 39;
		public static const KEY_SPACE:int 		= 32;
		public static const KEY_ESC:int 		= 27;
		public static const KEY_ENTER:int 		= 13;
		public static const KEY_DELETE:int 		= 46;
		public static const KEY_P:int 			= 80;
		public static const KEY_Q:int 			= 81;
		public static const KEY_W:int 			= 87;
		public static const KEY_NUM_PLUS:int 	= 107;
		public static const KEY_NUM_MINUS:int 	= 109;
		public static const KEY_NUM_STAR:int 	= 106;
		
		// 
		public static function register(stage:Stage):void
		{
			m_stage = stage;
			m_stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler, false, 0, true);
			m_stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler, false, 0, true);
		}
		
		public function release():void
		{
			m_stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
			m_stage.removeEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
			
			m_stage = null;
		}
	
		// Key up handler
		private static function keyUpHandler(evnt:KeyboardEvent):void 
		{
			for (var i:int = 0; i < m_keys.length; i++) 
			{
				if (m_keys[i] == evnt.keyCode) m_keys.splice(i, 1);
			}
		}
		
		// Key down handler
		private static function keyDownHandler(evnt:KeyboardEvent):void 
		{
			var key:int = evnt.keyCode;
 
			for (var i:int = 0; i < m_keys.length; i++) 
			{
				if (m_keys[i] == key) return;
			}
			m_keys.push(key);
		}
 
		public static function isKeyDown(key:int):Boolean
		{
			for (var i:int = 0; i < m_keys.length; i++) 
			{
				if (m_keys[i] == key) return true;
			}
			return false;
		}
 
		public static function get lastPressed():int 
		{ 
			return m_keys.length ? m_keys[m_keys.length - 1] : 0;
		}
 
		static public function get enabled():Boolean { return m_enabled; }
 
		// Enable/disable input system
		static public function set enabled(value:Boolean):void 
		{
			if (m_enabled == value) return;
			m_enabled = value;
			m_keys = [];
			if (m_enabled)
			{
				m_stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler, false, 0, true);
				m_stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler, false, 0, true);
			}else
			{
				m_stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
				m_stage.removeEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
			}
		}
 
	}
 
}